package com.jlect.swebing.renderers.gwt.client;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.Widget;
import com.jlect.swebing.renderers.client.*;

/**
 * Base implementation of the text based GWT renderer
 *
 * @author Sergey Kozmin
 * @since 21.11.2007 9:53:52
 */
public abstract class TextRendererBase extends AbstractGWTRenderer implements TextFieldRenderer, ClickListener, ChangeListener {
    private RendererActionListener eventListener;
    private RendererEvent event;

    public void setText(String text) {
        getTextBoxBase().setText(text);
    }

    public String getText() {
        return getTextBoxBase().getText();
    }

    public void setActionListener(RendererActionListener listener) {
        eventListener = listener;
    }

    private TextBoxBase getTextBoxBase() {
        return (TextBoxBase) ((CompositeAttachEventProvider)getWidget()).getTargetWidget();
    }

    public void onClick(Widget sender) {
        if(eventListener != null) {
            if(event == null) {
                event = new ClickActionEvent(this, 0);//todo implement modifiers
            }
            eventListener.fireActionPerformed(event);
        }
    }

    public void setEnabled(boolean enabled) {
        getTextBoxBase().setEnabled(enabled);
    }

    public void onChange(Widget widget) {
        if(eventListener != null) {
            if(event == null) {
                event = new TextActionEvent(this, 0);//todo implement modifiers
            }
            eventListener.fireActionPerformed(event);
        }
    }

    protected Widget provideWidget() {
        TextBoxBase textBase = provideTextBase();
        textBase.addClickListener(this);
        textBase.addChangeListener(this);
        return new CompositeAttachEventProvider(textBase);
    }

    public abstract TextBoxBase provideTextBase();
}
